//
//  UserInfoViewModel.swift
//  Qianli
//
//  Created by qianli on 2024/11/21.
//

import Foundation
import SwiftyUserDefaults

class UserInfoViewModel : ObservableObject{
    static let shared = UserInfoViewModel()
    var userDeviceList : UserDeviceListModel?
    var inviteDurationData:InviteDurationData?
    var articleResultData:ArticleResultData?
    var completionHandler: ((_ result:Bool) -> Void)?
    var completionMsgHandler: ((_ result:Bool,_ msg:String) -> Void)?
    //MARK: - 获取账号信息
    func MuIZuRZXjs2PfsXX(completion: @escaping (Result<BaseData, Error>) -> Void){
        NetWorkManager.shared.provider.request(.apiGetUserInfo){ result in
            switch result{
            case .success(let response):
                do{
                    let decoder = JSONDecoder()
//                    decoder.dateDecodingStrategy = .iso8601
                    let userInfoResults = try decoder.decode(UserInfoResults.self, from: response.data)
                    if userInfoResults.code == 0{
                        if let user = userInfoResults.data{
                            Defaults[\.avatar] = user.avatar
                            Defaults[\.username] = user.userName
                            Defaults[\.invitationCode] = user.invitationCode
                            Defaults[\.memberexpiryat] = user.memberExpiryAt
                            Defaults[\.memberLevel] = user.memberLevel
                            Defaults[\.isGuset] = user.guest
                            Defaults[\.isTester] = user.tester
                            Defaults[\.maxBindCount] = user.maxDevices
                            completion(.success(BaseData(code: 0, msg: "")))
                        }else{
                            completion(.success(BaseData(code: -1, msg: LocalizedString("Invalid user data"))))
                            ZacollectModel.shared.vnveDBhaItvpywSl("getUserInfo","无效data")
                        }
                    }else{
                        completion(.success(BaseData(code: userInfoResults.code, msg: userInfoResults.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("getUserInfo","\(userInfoResults.code)-\(userInfoResults.msg)")
                    }
                }catch{
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("getUserInfo","处理出错:\(error.localizedDescription)")
                }
                break
            case .failure(let error):
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("getUserInfo","请求出错:\(error.localizedDescription)")
                break
            }
        }
    }
    //MARK: - 绑定的设备列表
    func JOxbbBuNr3loTKi4(completion: @escaping (Result<BaseData, Error>) -> Void){
        NetWorkManager.shared.provider.request(.apiGetUserDeviceList){ [weak self] result in
            switch result{
            case .success(let response):
                do {
                    let userDeviceListResults = try JSONDecoder().decode(UserDeviceListResults.self, from: response.data)
                    if (userDeviceListResults.code == 0){
                        if let userDeviceList = userDeviceListResults.data{
                            self?.userDeviceList = userDeviceList
                            completion(.success(BaseData(code: 0, msg: "")))
                        }else{
                            completion(.success(BaseData(code: -1, msg: LocalizedString("Error Data"))))
                            ZacollectModel.shared.vnveDBhaItvpywSl("getUserDeviceList","无效data")
                        }
                    }else{
                        completion(.success(BaseData(code: userDeviceListResults.code, msg: userDeviceListResults.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("getUserDeviceList","\(userDeviceListResults.code)-\(userDeviceListResults.msg)")
                        
                    }
                } catch {
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("getUserDeviceList","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("getUserDeviceList","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    //MARK: - 解绑指定设备
    func ofuUSDfMhcfgsObm(deviceId:String,completion:@escaping (Result<BaseData,Error>)->Void){
        NetWorkManager.shared.provider.request(.apiDeleteUserDevice(deviceId: deviceId)) { [weak self] result in
            switch result{
            case .success(let response):
                do {
                    let deleteResult = try JSONDecoder().decode(BaseData.self, from: response.data)
                    if deleteResult.code==0{
                        completion(.success(deleteResult))
                    }else{
                        completion(.success(BaseData(code: deleteResult.code, msg: deleteResult.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("deleteUserDeviceList","\(deleteResult.code)-\(deleteResult.msg)")
                    }
                } catch {
                    print("deleteUserDeviceList json error : \(error)")
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("deleteUserDeviceList","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                print("deleteUserDeviceList error : \(error)")
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("deleteUserDeviceList","请求出错:\(error.localizedDescription)")
            }
        }
    }

    func ueuKslIIdjLNdJCA(userName:String,pw:String,completion:@escaping (Result<BaseData,Error>)->Void){
        NetWorkManager.shared.provider.request(.apiDeleteUserAccount(userName: userName, pw: pw)) {result in
            switch result{
            case .success(let response):
                do {
                    let deleteResult = try JSONDecoder().decode(BaseData.self, from: response.data)
                    if deleteResult.code == 0 {
                        completion(.success(BaseData(code: 0, msg: "")))
                    }else{
                        completion(.success(BaseData(code: deleteResult.code, msg: deleteResult.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("deleteAccount","\(deleteResult.code)-\(deleteResult.msg)")
                    }
                } catch {
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("deleteAccount","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("deleteAccount","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    func BfVcQQfbTmL5UsRU(_ invitecode:String){
        NetWorkManager.shared.provider.request(.apiBindReferrerUser(referrer_code: invitecode)){ [weak self] result in
            switch result{
            case .success(let response):
                do {
                    let backResult = try JSONDecoder().decode(BaseData.self, from: response.data)
                    if (backResult.code != 0){
                        self?.completionMsgHandler?(false,backResult.msg)
                    }else{
                        self?.completionMsgHandler?(true,backResult.msg)
                        ZacollectModel.shared.vnveDBhaItvpywSl("bindReferrerUser","\(backResult.code)-\(backResult.msg)")
                    }
                } catch{
                    QianliUniversalFunc.QianliLog("bindReferrerUser json error : \(error)")
                    let errtitle = LocalizedString("Error binding invitation")
                    self?.completionMsgHandler?(false,"\(errtitle):\(error.localizedDescription)")
                    ZacollectModel.shared.vnveDBhaItvpywSl("bindReferrerUser","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                QianliUniversalFunc.QianliLog("bindReferrerUser error: \(error)")
                let errtitle = LocalizedString("Failed to bind invitation code")
                self?.completionMsgHandler?(false,"\(errtitle)：\(error.localizedDescription)")
                ZacollectModel.shared.vnveDBhaItvpywSl("bindReferrerUser","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    func AK7x06pAg9dXtdB1(pagination:Pagination){
        NetWorkManager.shared.provider.request(.apiGetDurationBonusStatement(pagination: pagination)){ [weak self] result in
            switch result {
            case .success(let response):
                print("getOrderList success")
                do {
                    let decoder = JSONDecoder()
//                    decoder.dateDecodingStrategy = .iso8601
                    let inviteDurationResult = try decoder.decode(InviteDurationResult.self, from: response.data)
                    self?.inviteDurationData = inviteDurationResult.data
                    self?.completionMsgHandler?(true,"")
                } catch {
                    print("getOrderList json error : \(error)")
                    let errtitle =  LocalizedString("Error Data")
                    self?.completionMsgHandler?(false,"\(errtitle)：\(error.localizedDescription)")
                    ZacollectModel.shared.vnveDBhaItvpywSl("getInviteDurationBonusStatement","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                print("getOrderList failure error : \(error)")
                let errtitle = LocalizedString("Failed to request data")
                self?.completionMsgHandler?(false,"\(errtitle)：\(error.localizedDescription)")
                ZacollectModel.shared.vnveDBhaItvpywSl("getInviteDurationBonusStatement","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    func a6MH0MGhx9xhDERm(announcementRequest : AnnouncementRequest,completion:@escaping (Result<BaseData,Error>)->Void){
        NetWorkManager.shared.provider.request(.apiGetArticleList(announcementRequest: announcementRequest)){ [weak self] result in
            switch result {
            case .success(let response):
                do {
                    let decoder = JSONDecoder()
                    let articleResult = try decoder.decode(ArticleResults.self, from: response.data)
                    if articleResult.code == 0 {
                        self?.articleResultData = articleResult.data
                        completion(.success(BaseData(code: 0, msg: "")))
                    }else{
                        completion(.success(BaseData(code: articleResult.code, msg: articleResult.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("getArticleNotiList","\(articleResult.code)-\(articleResult.msg)")
                    }
                    
                } catch {
                    completion(.failure(error))
//                    let errtitle =  LocalizedString("Error Data")
                    ZacollectModel.shared.vnveDBhaItvpywSl("getArticleNotiList","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                completion(.failure(error))
//                let errtitle = LocalizedString("Failed to request data")
                ZacollectModel.shared.vnveDBhaItvpywSl("getArticleNotiList","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
}
